/**
 * create by young (young2f@outlook.com) on 2023/4/16
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const table = 'Material';
module.exports = class extends base {
  async create(body) {
    const { ctx } = this;
    const result = await ctx.app.dbs.insert(table, body);
  //  const result = result1 && await ctx.app.dbs.insert('Store', body);
    return { status: 'ok', result };
  }

  async findMany(body) {
    const { ctx } = this;
    const { name, code } = body;

    if (name) body['name'] = { $regex: name };
    if (code) body['code'] = { $regex: code };

    const res = await ctx.app.dbs.aggregate(table, [
      { $match: { ...body } },
      { $sort: { createdTs: -1 } },
    ]);
    const result = [];
    _.map(res, item => {
      const { labels } = item;
      _.map(labels, it => {
        _.assign(item, it);
      });
      result.push(item);
    });
    return { status: 'ok', result };
  }

  async findOne(body) {
    const { tenantCode, code } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.findOne(table, { tenantCode, code });
    return { status: 'ok', result };
  }

  async updateOne(body) {
    const { tenantCode, code } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.updateOne(table, { tenantCode, code }, body);
  //  const result = result1 && await ctx.app.dbs.updateOne('Store', { tenantCode, code }, body);
    return { status: 'ok', result };
  }
  async updateStoreCount(body) {
    const { tenantCode, code,storeCount,tenantName,createUser,createUsername } = body;
    const { ctx } = this;
    const result = await ctx.app.dbs.updateOne(table, { tenantCode, code }, { storeCount });
    const history = {
      table,
      name: '调整库存记录' + storeCount,
      tenantCode,
      code,
      tenantName,
      createUser,
      createUsername,
      createdTs:new Date().toISOString(),
    };
    const historyRes = await ctx.app.dbs.insert('History', history);
    return { status: 'ok', result };
  }

  async deleteOne(body) {
    const { tenantCode, code } = body;
    const { ctx } = this;
    const order = await ctx.app.dbs.findOne('ProcureOrder', { tenantCode, 'materialBody.code': code });
    if (order) {
      throw new Error('删除失败！此物料已在采购单中引用！');
    }
    const result = await ctx.app.dbs.deleteOne(table, { tenantCode, code });
   // const result = result1 && await ctx.app.dbs.deleteOne('Store', { tenantCode, code });
    return { status: 'ok', result };
  }
};
